package pasientlosjen.DAO;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pasientlosjen.entities.Artikkel;
import pasientlosjen.services.EMF;

public class GenericDaoImpl<T, PK> implements GenericDao<T, PK> {
	private EntityManager entityManager;

	public boolean create(T o) {

		EntityTransaction transaction = getTransaction();
		transaction.begin();
		entityManager.persist(o);
		transaction.commit();
		entityManager.close();
		return true;
	}

	public T read(Class<T> type, PK id) {
		entityManager = EMF.get().createEntityManager();
		T resultat = (T) entityManager.find(type, id);
		entityManager.close();
		return resultat;
	}

	public boolean update(T o) {

		// getTransaction().update(o);
		return true;
	}

	public boolean delete(T o) {
		// getTransaction().delete(o);
		return true;
	}

	public List<T> readAll(Class<?> type) {
		entityManager = EMF.get().createEntityManager();
		List<T> resultat = (List<T>) entityManager.createQuery("SELECT  FROM " + Artikkel.class.getName())
				.getResultList();
		// entityManager.close();
		return resultat;
	}

	private EntityTransaction getTransaction() {
		entityManager = EMF.get().createEntityManager();
		return entityManager.getTransaction();
	}

}